#include <Parallel.h>
#include <csp_debug.h>
#include <csp_misc.h>
#include <shared_data.h>
#include <Scheduler.h>
#include <stdio.h>
#include <CSPProcess.h>
#include <ProcessComposition.h>


Parallel::Parallel(CSPProcess *p1, ...)
{
	CSPProcess *p;
	va_list ap;

	has_run = 0;

	ASSERT(p1);

	va_start(ap, p1);
	p = p1;
	do{
		procs.push_back(p);
	} while( (p = va_arg(ap, CSPProcess*)) );
	va_end(ap);
}

void
Parallel::Add(CSPProcess *p){
	if( has_run ){
		Failure();	
	}
	procs.push_back(p);
}

	void
Parallel::Failure()
{
	printf("Processes can only be executed once.\n");
	exit(-1);
}

int
Parallel::Run(){
	ProcessComposition *p;
	if( has_run ){
		Failure();	
	}

	event = new ProcessTerminationEvent(procs.size());



	for(unsigned int i=0;i < procs.size(); i++) {
		//p = new ProcessComposition( procs.at(i)->GetMnemonic() ,event, NULL);
		p = procs.at(i)->GetProcessComposition();

		p->SetEvent(event, NULL);

		p->Schedule();
	}



	return event->WaitForProcessTermination();
}
